package com.zzh.zzhaiagent.wx.handler;

import com.zzh.zzhaiagent.wx.service.WxMsgService;
import jakarta.annotation.Resource;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Map;


/**
 * @author ZZH
 * 这个Handler主要是处理扫描二维码事件 当二维码扫码后，会触发这个事件
 * 扫码成功进来就是要去获取用户的权限信息的！并且让用户进行授权！
 */
@Component
public class ScanHandler extends AbstractHandler {

    // 授权链接 注意替换为自己的appid和redirect_uri授权成功回调的地址,以及scope=snsapi_userinfo
    // 注意：这里的redirect_uri需要在微信公众平台中配置，并且需要在微信公众平台中配置授权成功回调的地址
    public static final String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

    @Value("${wx.mp.callback}")
    private String callback;

    @Resource
    private WxMsgService wxMsgService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map,
                                    WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {
        // 扫码事件处理
        // 拼接授权url
        WxMpXmlOutMessage response = null;
        try {
            response = wxMsgService.scan(wxMpService, wxMpXmlMessage);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return response;
    }

}
